package ws

import (
	"fmt"
	"sync"
	"sync/atomic"

	"gitee.com/AlexWoo/arpc"
	"gitee.com/AlexWoo/arpc/alog"
	"gitee.com/AlexWoo/arpc/anet"
	"github.com/fasthttp/websocket"
)

var (
	cid uint64 = 0
)

func newConnection(conf *alog.LogConf) *Connection {
	c := &Connection{
		conn:             nil,
		id:               atomic.AddUint64(&cid, 1),
		closed:           0,
		serial:           0,
		isClient:         false,
		retryIntervalSec: 0,
	}

	c.lctx = &alog.LogCtx{
		Prefix:   c.Prefix,
		Suffix:   c.Suffix,
		LogLevel: alog.Level[conf.LogLevel],
	}

	return c
}

// A Connction is related with one user
// When User reconnect, conn will re-related to connection
type Connection struct {
	conn   *websocket.Conn
	id     uint64
	closed uint32 // 0 unclosed, 1 closed

	serial uint64

	h    anet.Handler
	lock sync.Mutex

	// for log
	lctx   *alog.LogCtx
	remote string
	local  string

	// for client
	isClient         bool
	retryIntervalSec uint32
	onConnect        anet.OnConnect
	onDisconnect     anet.OnDisconnect
}

func (c *Connection) loop() {
	defer func() {
		c.lock.Lock()
		defer c.lock.Unlock()

		if c.closed != 1 {
			err := c.conn.Close()
			alog.LogError(c.lctx, "Connection close error: %v", err)
		}

		c.conn = nil
	}()

	for {
		t, data, err := c.conn.ReadMessage()
		if err != nil {
			alog.LogError(c.lctx, "ReadMessage Error %v", err)
			return
		}

		if t != websocket.BinaryMessage { // 非预期消息类型
			alog.LogError(c.lctx, "Unexpected message type %d", t)
			continue
		}

		c.h.OnMsg(c, data)
	}
}

func (c *Connection) Send(bts []byte) error {
	// https://pkg.go.dev/github.com/gorilla/websocket#hdr-Concurrency
	// Applications are responsible for ensuring that
	// no more than one goroutine calls the write methods
	// (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON,
	// EnableWriteCompression, SetCompressionLevel) concurrently
	// and that no more than one goroutine calls the read methods
	// (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler,
	// SetPingHandler) concurrently.
	c.lock.Lock()
	defer c.lock.Unlock()

	if c.conn == nil {
		err := fmt.Errorf("Send message: %s but connection is closed", string(bts))
		arpc.Errorf("%v", err)
		return err
	}

	alog.LogDebug(c.lctx, "Send message: %s")

	err := c.conn.WriteMessage(websocket.BinaryMessage, bts)
	if err != nil {
		alog.LogError(c.lctx, "Send error, %v", err)
	}

	return err
}

func (c *Connection) Close() {
	closed := atomic.SwapUint32(&c.closed, 1)
	if closed == 1 {
		return
	}

	c.conn.Close()
}

func (c *Connection) Lctx() *alog.LogCtx {
	return c.lctx
}

func (c *Connection) Prefix() string {
	return fmt.Sprintf("*%d", c.id)
}

func (c *Connection) Suffix() string {
	if c.conn != nil {
		return fmt.Sprintf("remote: %s, local: %s", c.remote, c.local)
	}

	return ""
}
